package com.dc.free.util;

import com.jfinal.kit.PathKit;
import com.jfinal.kit.Prop;
import com.jfinal.kit.PropKit;
import com.jfinal.plugin.activerecord.dialect.Dialect;
import com.jfinal.plugin.druid.DruidPlugin;

public class DruidPluginUtil {
	private static Prop p = PropKit.use("config.properties");
	private static String jdbcType = p.get("jdbc.type");
	private static String dialectClass = p.get(String.format("jdbc.%s.dialect.class", jdbcType));
	
	/**
	 * 插件初始化
	 * @return
	 */
	public static DruidPlugin create() {
		String jdbcUrl = p.get(String.format("jdbc.%s.url", jdbcType));
		String jdbcUser = p.get(String.format("jdbc.%s.user", jdbcType));
		String jdbcPassword = p.get(String.format("jdbc.%s.password", jdbcType));
		String driverClass = p.get(String.format("jdbc.%s.driver.class", jdbcType));
		
		if("sqlite".equalsIgnoreCase(jdbcType)){
			jdbcUrl = String.format(jdbcUrl, PathKit.getWebRootPath());
		}
		
		return new DruidPlugin(jdbcUrl, jdbcUser, jdbcPassword).setDriverClass(driverClass);
	}
	
	/**
	 * 获取方言
	 * @return
	 */
	public static Dialect getDialect() {
		Dialect dialect = null;
		try {
			dialect = (Dialect) Class.forName(dialectClass).newInstance();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return dialect;
	}
}
